package cn.ac.cintcm.synonymous;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class FilteredDatasource extends DataSource {
    private DataSource ds;

    public FilteredDatasource(DataSource ds) {
        this.ds = ds;
        copyField(ds);
    }

    public DataSource filterState(String state) {
        String[][] originalData = ds.getData();
        if (originalData != null && state != null && !state.trim().equals("")) {
            List<String[]> array = new ArrayList<String[]>();
            array.add(data[0]);
            idMap = new HashMap<String, Integer>();
            int j = 1;
            for (int i = 1; i < originalData.length; i++) {
                if (originalData[i][getFieldIndex(STATE)].equals(state)) {
                    array.add(originalData[i]);
                    idMap.put(originalData[i][getFieldIndex(ID)], j++);
                }
            }
            data = array.toArray(new String[0][0]);
        }
        return this;
    }
    
    public DataSource filterId(String[] ids) {
        String[][] originalData = ds.getData();
        if (ids != null) {
            List<String[]> array = new ArrayList<String[]>();
            array.add(data[0]);
            Arrays.sort(ids);
            idMap = new HashMap<String, Integer>();
            int j = 1;
            for (int i = 1, k = 0; k < ids.length && i < originalData.length; i++) {
                if (originalData[i][getFieldIndex(ID)].equals(ids[k])) {
                    array.add(originalData[i]);
                    idMap.put(originalData[i][getFieldIndex(ID)], j++);
                    k++;
                }
            }
            data = array.toArray(new String[0][0]);
        }
        return this;
    }
    
    @Override
    public Message write() {
        return ds.write();
    }

}
